#include <queue>
#include <vector>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    explicit ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution
{
public:
    ListNode* reverseKGroup(ListNode* head, int k)
    {
        int n = 0;
        ListNode* i = head;
        while(i)
        {
            i = i->next;
            n++;
        }
        n /= k;

        ListNode* newhead = new ListNode(0);
        ListNode* prev = newhead;
        ListNode* cur = head;
        for(int i=0; i<n; i++)
        {
            ListNode* tmp = cur;
            for(int j=0; j<k; j++)
            {
                ListNode* next = cur->next;
                cur->next = prev->next;
                prev->next = cur;
                cur = next;
            }
            prev = tmp;
        }
        prev->next = cur;
        prev = newhead->next;
        delete newhead;
        return prev;
    }
};